/*
 * @Author: 
 * @Date: 2022-02-15 15:19:57
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-15 15:21:14
 * @Description: 请填写简介
 */
import url from "url";
import WebSocket from "ws";
import debug from "debug";
import moment from "moment";
import { Ticket } from "./Ticket";

const debugInfo = debug("server:global");

// server 可以是http server 实例
const wss = new WebSocket.Server({ server });
wss.on("connection", async (ws) => {
  const location = url.parse(ws.upgradeReq.url, true);
  const cookie = ws.upgradeReq.cookie;
  debugInfo("ws request from:" + location, "cookies:", cookie);
  // issue & send ticket to the peer
  if (!checkIdentify(ws)) {
    terminate(ws);
  } else {
    const ticket = issueTicket(ws);
    await ticket.save();
    ws.send(ticket.pojo());
    ws.on("message", (message) => {
      if (!checkTicket(ws, message)) {
        terminate(ws);
      }
      debugInfo("received:%s", message);
    });
  }
});
function issueTicket(ws) {
  const uniqueId = ws.upgradeReq.connection.remoteAddress;
  return new Ticket(uniqueId);
}
async function checkTicket(ws, message) {
  const uniqueId = ws.upgrade.connection.remoteAddress;
  const record = await Ticket.get(uniqueId);
  const token = message.token;
  return (
    record &&
    record.expires &&
    record.token &&
    record.token === token &&
    moment(record.expires) >= moment()
  );
}
// 身份检查，可填入具体检查逻辑
function checkIdentity(ws) {
  return true;
}
function terminate(ws) {
  ws.send("BYE!");
  ws.close();
}